import { reqGetCode, reqUserInfo,reqLogin, reqRegister, reqLogout } from "@/api"
import { getToken, removeToken } from "@/utils/token"

const state = {
    code:"",
    token:getToken(),
    userInfo:{}
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    CLEAR(state){
        state.token = ''
        state.userInfo = []
        removeToken()
    }
}
const actions = {
    // 获取验证码
    async getCode({commit},mobile){
        //console.log(mobile)
        let result = await reqGetCode(mobile)
        // console.log(result)
        if(result.code == 200){
            commit("GETCODE",result.data)
            return "ok"
        }else{
            return Promise.reject(new Error("fail"))
        }

    },

    // 注册
    async register({commit},params){
        let result = await reqRegister(params)
        console.log(result)
        if(result.code == 200){
            commit("GETCODE",result.data)
            // 存储用户信息
            return "ok"
        }else{
            return Promise.reject(result.message)
        }
    },
    //登陆
    async login({commit},params){
        let result = await reqLogin(params)
        //console.log(result)
        if(result.code == 200){
            commit("USERLOGIN",result.data.token)
            localStorage.setItem("TOKEN",result.data.token)
            return "ok"
        }else{
            return Promise.reject(result.message)
        }
    },
    // 退出登陆
    async userLogout({commit}){
        let result = await reqLogout()
        if(result.code == 200){
            commit("CLEAR")
            return "ok"
        }else{
            return Promise.reject(result.message)
        }
    },

    async getUserInfo({commit}){
        let result = await reqUserInfo()  
        //console.log(result)     
        if(result.code == 200){
            commit("GETUSERINFO",result.data)
            return result.data
        }else{
            return Promise.reject(result)
        }
    }
}
const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters
}